package com.bookcity.utils;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @Author: Trioutia
 * @Date: 2022/5/24 - 05 - 24 - 18:25
 * @Description: com.bookcity.utils
 * @version: 1.0
 */
public class UtilArray {

    //  计算某个值出现的个数
    public static long countOccurrences(int[] numbers, int value) {
        return Arrays.stream(numbers)
                .filter(number -> number == value)
                .count();
    }

    //  数组扁平化
    public static int[] deepFlatten(Object[] input) {
        return Arrays.stream(input)
                .flatMapToInt(o -> {
                    if (o instanceof Object[]) {
                        return Arrays.stream(deepFlatten((Object[]) o));
                    }
                    return IntStream.of((Integer) o);
                }).toArray();
    }

    //  两个数组间的差异, 只保留second不包含的值
    public static int[] difference(int[] first, int[] second) {
        Set<Integer> set = Arrays.stream(second).boxed().collect(Collectors.toSet());
        return Arrays.stream(first)
                .filter(v -> !set.contains(v))
                .toArray();
    }

    //  剔除重复元素
    public static Object[] distinctValuesOfArray(Object[] elements) {
        return Arrays.stream(elements).distinct().toArray();
    }

    //  从数组中随机返回一个元素
    public static <T> T sample(T[] arr) {
        return arr[(int) Math.floor(Math.random() * arr.length)];
    }

}
